package com.sky.service.impl;

import com.github.xiaoymin.knife4j.core.util.StrUtil;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.result.Result;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 42
 * @date 2025/4/6
 * @Description
 */
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result<TurnoverReportVO> turnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> list = new ArrayList<>();
        //日期时间的设置
        list.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            list.add(begin);
        }

        List<Object> turnList = new ArrayList<>();
        //营业额的统计
        for (LocalDate date : list) {
            LocalDateTime min = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime max = LocalDateTime.of(date, LocalTime.MAX);
            Map<String, Object> map = new HashMap<>();
            map.put("begin",min);
            map.put("end",max);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnList.add(turnover);
        }

        String dateString = StringUtils.join(list, "，");
        String turnString = StringUtils.join(turnList, ",");
        TurnoverReportVO build = TurnoverReportVO.builder().dateList(dateString).turnoverList(turnString).build();
        return Result.success(build);
    }

    /**
     * 用户统计接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result<UserReportVO> userStatistics(LocalDate begin, LocalDate end) {

        //1.存放日期的列表
        List<LocalDate> list = new ArrayList<>();
        list.add(begin);
        while (!begin.equals(end)){
           begin = begin.plusDays(1);
           list.add(begin);
        }

        //2.遍历日期列表，查询数据
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        for (LocalDate localDate : list) {
            //当天最早
            LocalDateTime min = LocalDateTime.of(localDate, LocalTime.MIN);
            //当天最晚
            LocalDateTime max = LocalDateTime.of(localDate, LocalTime.MAX);

            //考虑共用接口
            //SELECT COUNT(*) FROM user WHERE create_time <= max;
            //用户总数
            Integer totalUser = userMapper.getUserCount(null,max);
            //SELECT COUNT(*) FROM user WHERE create_time >= min AND create_time <= max;
            //当天新增用户
            Integer newUser = userMapper.getUserCount(min,max);

            totalUserList.add(totalUser);
            newUserList.add(newUser);
        }

        UserReportVO userReportVO = new UserReportVO();
        String dateList = StringUtils.join(list, ",");
        String newList = StringUtils.join(newUserList, ",");
        String totalList = StringUtils.join(totalUserList, ",");
        userReportVO.setDateList(dateList);
        userReportVO.setNewUserList(newList);
        userReportVO.setTotalUserList(totalList);


        return Result.success(userReportVO);
    }

    /**
     * 订单统计接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result<OrderReportVO> orderStatistics(LocalDate begin, LocalDate end) {

         //1.日期集合
         List<LocalDate> list = new ArrayList<>();
         list.add(begin);
         while (!begin.equals(end)){
             begin = begin.plusDays(1);
             list.add(begin);
         }

         List<Integer> orderCountList = new ArrayList<>();
         List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : list) {
            LocalDateTime min = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime max = LocalDateTime.of(date, LocalTime.MAX);
            //1.查询每日订单数
            //SELECT COUNT(*) FROM orders WHERE order_time >= min and order_time <= max;
            Integer orderCount = orderMapper.getOrderCount(min,max,null);

            //2.查询每日有效订单数
            //SELECT COUNT(*) FROM orders WHERE order_time >= min and order_time <= max and status = 5
            Integer validCount = orderMapper.getOrderCount(min,max,Orders.COMPLETED);

            orderCountList.add(orderCount);
            validOrderCountList.add(validCount);
        }

        //采用stream流的方式去累加，reduce方法可以对所有元素进行一个二元计算的操作
        Integer totalOrderCount = orderCountList.stream().reduce(0, Integer::sum);

        Integer validOrderCount = validOrderCountList.stream().reduce(0, Integer::sum);

        Double orderCompletionRate = 0.0;
        if(totalOrderCount!=0){
            orderCompletionRate = validOrderCount.doubleValue()/totalOrderCount;
        }

//        StringUtils.join(list,",")
        OrderReportVO reportVO = OrderReportVO.builder()
                .dateList(StringUtils.join(list, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();

        return Result.success(reportVO);
    }

    /**
     * 统计top10的销量数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result<SalesTop10ReportVO> top10Statistics(LocalDate begin, LocalDate end) {
        LocalDateTime min = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime max = LocalDateTime.of(end, LocalTime.MAX);


        //SELECT od.name AS name,COUNT(*) AS number FROM orders o JOIN order_detail od ON o.id = od.order_id
        //WHERE o.order_time >= min AND o.order_time <= max AND status = 5
        //GROUP BY od.name
        //ORDER BY number DESC
        //LIMIT 10
        List<GoodsSalesDTO> list = orderMapper.getTop10Statistics(min,max);

        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();
        for (GoodsSalesDTO goodsSalesDTO : list) {
            nameList.add(goodsSalesDTO.getName());
            numberList.add(goodsSalesDTO.getNumber());
        }

        SalesTop10ReportVO reportVO = SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();


        return Result.success(reportVO);
    }

    /**导出近30天的运营数据报表
     * @param response
     **/
    public void exportBusinessData(HttpServletResponse response) {
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        //查询概览运营数据，提供给Excel模板文件
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin,LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //基于提供好的模板文件创建一个新的Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            //获得Excel文件中的一个Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);
            //获得第4行
            XSSFRow row = sheet.getRow(3);
            //获取单元格
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                //准备明细数据
                businessData = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //通过输出流将文件下载到客户端浏览器中
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.flush();
            out.close();
            excel.close();

        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
